package com.trade.okxserver.clr.trade;

import com.google.gson.Gson;
import com.trade.okxserver.api.PublicData;
import com.trade.okxserver.constants.UrlConstants;
import com.trade.okxserver.manage.SecondKlineCache;
import com.trade.okxserver.res.PublicDataRes;
import com.trade.okxserver.ws.SimpleWebSocketClient;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.drafts.Draft_6455;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.List;

@Slf4j
@Component
public class TradeChannel implements CommandLineRunner {

    private final static Gson GSON = new Gson();

    @Resource
    PublicData publicData;

    @Override
    @SneakyThrows
    public void run(String... args) {
        log.info("开始创建websocket连接订阅K线数据");
        List<PublicDataRes> instruments = publicData.instruments(null);
        try {
            for (PublicDataRes publicDataRes : instruments) {
                if("sats-usdt-swap".equalsIgnoreCase(publicDataRes.getInstId()) ||
                        "sweat-usdt-swap".equalsIgnoreCase(publicDataRes.getInstId()) ||
                        "turbo-usdt-swap  ".equalsIgnoreCase(publicDataRes.getInstId()) ){
                    log.info(GSON.toJson(publicDataRes));
                }
                SimpleWebSocketClient<PublicDataRes> client = new SimpleWebSocketClient(new URI(UrlConstants.WS_BUSINESS_URL), new Draft_6455(), publicDataRes);
                client.setOpenHandle((item) -> {
                    String data = "{\"op\":\"subscribe\",\"args\":[{\"channel\":\"candle1s\",\"instId\":\"" + item.getInstId() + "\"}]}";
                    client.send(data);
                });
                client.setMessageHandle((message) -> {
                    ChannelData channelData = GSON.fromJson(message, ChannelData.class);
                    String instId = channelData.getArg().getInstId();
                    List<List<Double>> data = channelData.getData();
                    SecondKlineCache.set(instId, data);

                });
                client.connect();
                Thread.sleep(50);
            }
            log.info("创建websocket连接订阅K线数据完成");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
